package com.lw.lwte.testengin.listener;

import com.lw.lwte.common.util.ScreenshotTool;
import org.testng.ITestResult;
import org.testng.Reporter;

import java.awt.*;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class BasicUICaseListener extends BasicCaseListener {
    public static final String OUTPUT_PATH = String.format("%s/target/lwte-result/report/failScreen", System.getProperty("user.dir"));
    public static ScreenshotTool screenshotTool;

    static {
        try {
            screenshotTool = new ScreenshotTool();
        } catch (AWTException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void onTestFailure(ITestResult tr) {
        super.onTestFailure(tr);
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
        String name = tr.getName() + "-" + timestamp + ".png";

        Reporter.log(String.format("UI自动化执行失败，截图: %s", name),true);
        // 捕获整个屏幕的截图并保存到当前目录下的screenshot.png文件
        try {
            screenshotTool.captureFullScreen(String.format("%s//%s", OUTPUT_PATH, name));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
